﻿using Microsoft.Extensions.Options;
using Sgr;
using Sgr.BackGroundTasks;
using Sgr.Utilities;

namespace Microsoft.AspNetCore.Builder
{
    public static class ApplicationBuilderExtensions
    {
        /// <summary>
        /// 启动所有的后台周期性任务
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder ReStartAllRecurringTasks(this IApplicationBuilder app)
        {
            Check.NotNull(app, nameof(app));

            var recurringTaskManager = app.ApplicationServices.GetRequiredService<IRecurringTaskManager>();
            var backGroundTaskOptions = app.ApplicationServices.GetRequiredService<IOptions<BackGroundTaskOptions>>().Value;
            var logger = app.ApplicationServices.GetService<ILogger<IRecurringTaskManager>>();

            AsyncHelper.RunSync(async () =>
            {
                try
                {
                    var taskIds = backGroundTaskOptions.GetAllRecurringTaskIds();

                    if (taskIds == null || taskIds.Count == 0)
                    {
                        logger?.LogInformation("未发现已注册的周期性任务");
                        return;
                    }

                    logger?.LogInformation("开始启动周期性后台任务，共发现 {TaskCount} 个任务", taskIds.Count);

                    int successCount = 0;
                    int failCount = 0;
                    var failedTasks = new List<string>();

                    foreach (var taskId in taskIds)
                    {
                        try
                        {
                            await recurringTaskManager.ReStartAsync(taskId);

                            successCount++;
                            logger?.LogDebug("任务启动成功: {TaskId}", taskId);
                        }
                        catch (Exception ex)
                        {
                            failCount++;
                            failedTasks.Add(taskId);
                            logger?.LogError(ex, "任务启动失败: {TaskId}", taskId);
                        }
                    }

                    logger?.LogInformation("周期性后台任务启动完成，成功: {SuccessCount}，失败: {FailCount}",
                        successCount, failCount);

                    if (failedTasks.Count > 0)
                    {
                        logger?.LogWarning("启动失败的任务列表: {FailedTasks}", string.Join(", ", failedTasks));
                    }
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex, "启动周期性后台任务时发生严重错误");
                }
            });

            return app;
        }
    }
}